package org.folio.rest.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.cql2pgjson.CQL2PgJSON;
import org.folio.cql2pgjson.exception.FieldException;
import org.folio.rest.RestVerticle;
import org.folio.rest.impl.other.PartyLogSave;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.impl.other.delayjob.partyattend.PartyAttendHandler;
import org.folio.rest.impl.other.delayjob.partydelay.PartyEndHandler;
import org.folio.rest.impl.other.notify.INotify;
import org.folio.rest.impl.other.reserve_station.ReserveStation;
import org.folio.rest.impl.other.take.TakeInterface;
import org.folio.rest.impl.other.take.TenantsTaskService;
import org.folio.rest.impl.service.AuxiliaryUpdateService;
import org.folio.rest.impl.util.LocalDateUtil;
import org.folio.rest.jaxrs.model.*;
import org.folio.rest.jaxrs.resource.PartyInfo;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.PostgresClient;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.utils.BinaryOutStream;
import org.folio.rest.tools.utils.ValidationHelper;

import javax.ws.rs.core.Response;
import java.util.*;

import static io.vertx.core.Future.succeededFuture;

/**
 * @author lee
 * @Classname PartyImpl
 * @Description TODO
 * @Date 2020/6/18 16:22
 * @Created by lee
 */
public class PartyInfoImpl implements PartyInfo {
 
    private final Logger logger = LoggerFactory.getLogger("modparty");

    private static final String NOTIFY_TABLE = "party";

    private CQLWrapper getCQL(String query, int limit, int offset) throws FieldException {
        return new CQLWrapper(new CQL2PgJSON(NOTIFY_TABLE + ".jsonb"), query, limit, offset);
    }


    @Override
    public void postPartyInfo(String lang, org.folio.rest.jaxrs.model.Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

       PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
       if (StrUtil.isBlankOrUndefined(entity.getFacId())){
          new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getVenueId(),entity.getVenue(),false,Integer.parseInt(entity.getVenueCount()),replys->{
              if (replys.succeeded()){
                  saveParty(entity, okapiHeaders, asyncResultHandler, pg);
              }else{
                  ValidationHelper.handleError(replys.cause(), asyncResultHandler);
              }
           });
           return;
       }else{
          new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getVenueId(),entity.getVenue(),false,Integer.parseInt(entity.getVenueCount()),replys->{
               if (replys.succeeded()){
                  new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(),entity.getFacName(),false,Integer.parseInt(entity.getFacCount()),reply->{
                       if (reply.succeeded()){
                           saveParty(entity, okapiHeaders, asyncResultHandler, pg);
                       }else{
                           ValidationHelper.handleError(replys.cause(), asyncResultHandler);
                       }

                   });
               }else{
                   ValidationHelper.handleError(replys.cause(), asyncResultHandler);
               }

           });
           return;
       }
    }

    private void saveParty(Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, PostgresClient pg) {
        String id = entity.getId();
        if (id == null || id.trim().isEmpty()) {
            id = UUID.randomUUID().toString();
        }
        entity.setState(0);
        entity.setIsCalendar(0);
        pg.save(NOTIFY_TABLE,id,entity,reply->{
            if(reply.succeeded())
            {
                String ret = reply.result();
                entity.setId(ret);

                asyncResultHandler.handle(succeededFuture(PostPartyInfoResponse
                        .respond201WithApplicationJson(entity, PostPartyInfoResponse.
                                headersFor201() )));
                PartyLogSave.saveLog("新增名称为【"+ entity.getPartyName() +"】的活动",2, entity.getMetadata(),entity.getOperator(),okapiHeaders,asyncResultHandler,pg);
            }else {
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }

        });
    }


    @Override
    public void getPartyInfo(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        CQLWrapper cql = null;
        if(StrUtil.isBlankOrUndefined(query))
        {
            query = null;
        }
        try {
            cql = getCQL(query, limit, offset);

        } catch (Exception e) {
            ValidationHelper.handleError(e, asyncResultHandler);
            return;
        }
        PgUtil.postgresClient(vertxContext, okapiHeaders)
                .get(NOTIFY_TABLE, org.folio.rest.jaxrs.model.PartyGroup.class, new String[]{"*"}, cql,
                        true , false ,
                        reply -> {
                            if (reply.succeeded()) {
                                PartyCollection notes = new PartyCollection();
                                List<PartyGroup> notifyList  = reply.result().getResults();
                                notes.setPartyGroup(notifyList);
                                Integer totalRecords = reply.result().getResultInfo().getTotalRecords();
                                notes.setTotalRecords(totalRecords);
                                asyncResultHandler.handle(succeededFuture(
                                        GetPartyInfoResponse.respond200WithApplicationJson(notes)));
                            } else {
                                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                            }
                        });
    }

    @Override
    public void getPartyInfoQrCodeAttendById(String id, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        if (StrUtil.isBlankOrUndefined(id)){
            logger.error("The  id  is null , check your request id" );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Your request ID is empty, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        createQRCode(id, okapiHeaders, asyncResultHandler, vertxContext,"attend");
    }

    private void createQRCode(String id, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext,String type) {
        CQLWrapper cql = null;
        String query = "isDel = 0 and code == MOBILE_REQUEST_HEAD ";
        try {
            cql = PartyUtil.getCQL(query, -1, -1, "party_set");
        } catch (Exception e) {
            // TODO: handle exception
            logger.debug(e);
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "系统找不到移动端二维码端请求头，请到活动配置一下,属性代码是【MOBILE_REQUEST_HEAD】的请求头");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
		}
        PgUtil.postgresClient(vertxContext,okapiHeaders).get("party_set", PartySetGroup.class,new String[]{"*"},cql,false,false, reply->{
            if (reply.succeeded()){
                List<PartySetGroup> result = reply.result().getResults();
                if(result == null || result.size() == 0) {
                	 Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                             "系统找不到移动端二维码端请求头，请到活动配置一下,属性代码是【MOBILE_REQUEST_HEAD】的请求头");
                     asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
                     return;
                }
                if(result.size()>1) {
                	Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                            "找到移动端二维码端请求头，有多条相同的配置，请清除无效的请求头");
                    asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
                    return;
                }
                PartySetGroup deploy = result.get(0);
                String url =null;
                if("attend".equals(type)) {
                    url = deploy.getContent()+"/#/reserve_all_detail/"+id;
                } else if("reserve".equals(type)){
                    url = deploy.getContent()+"/#/party_details/"+id;
                }
                byte[] value = QrCodeUtil.generatePng(url, 300, 300);
                BinaryOutStream binaryOutStream = new BinaryOutStream();
                binaryOutStream.setData(value);
                asyncResultHandler.handle(Future.succeededFuture(GetPartyInfoQrCodeAttendByIdResponse.respond200WithApplicationOctetStream(binaryOutStream)));

            }else{
            	 Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                         "找不到移动端二维码端请求头，请到活动配置一下,属性代码是【MOBILE_REQUEST_HEAD】的请求头");
                 asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
                 return;
            }
        });
    }

    @Override
    public void getPartyInfoQrCodeReserveById(String id, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

        if (StrUtil.isBlankOrUndefined(id)){
            logger.error("The  id  is null , check your request id" );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Your request ID is empty, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        createQRCode(id, okapiHeaders, asyncResultHandler, vertxContext,"reserve");
    }




    @Override
    public void getPartyInfoById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        String noteId = id;
        if (noteId == null ) {
            logger.error("The  id  is null , check your request id" );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                    "Your request ID is empty, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PgUtil.postgresClient(vertxContext, okapiHeaders)
                .getById(NOTIFY_TABLE,id,org.folio.rest.jaxrs.model.Party.class,callback->{
                    if (callback.failed()) {
                        ValidationHelper.handleError(callback.cause(), asyncResultHandler);
                        return;
                    }
                    if (callback.result() == null) {
                        asyncResultHandler.handle(succeededFuture(GetPartyInfoByIdResponse.respond404WithTextPlain(id)));
                        return;
                    }
                    asyncResultHandler.handle(succeededFuture(GetPartyInfoByIdResponse.respond200WithApplicationJson(callback.result())));
                });
    }

    @Override
    public void deletePartyInfoById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        String noteId = id;
        if (noteId == null ) {
            logger.error("The  id  is null , check your request id" );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                    "Your request ID is empty, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
        pg.getById(NOTIFY_TABLE,id,Party.class,reply-> {
            if (reply.succeeded()) {
                Party entity = reply.result();
                if (!StrUtil.isBlankOrUndefined(entity.getFacId() )&& !StrUtil.isBlankOrUndefined(entity.getFacCount())){
                   new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(),entity.getFacName(),true,Integer.parseInt(entity.getFacCount()),replys-> {
                            delPartyAndAuxiliary(id, okapiHeaders, asyncResultHandler, pg, entity,vertxContext);
                           if (replys.failed()){
                               logger.info(replys.cause().getMessage());
                           }
                           return;
                       });
                }else {
                            delPartyAndAuxiliary(id, okapiHeaders, asyncResultHandler, pg, entity,vertxContext);
                }
            }
        });


    }

    private void delPartyAndAuxiliary(String id, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, PostgresClient pg, Party entity, Context vertxContext) {
       new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getVenueId(), entity.getVenue(), true, Integer.parseInt(entity.getVenueCount()), r -> {

                pg.delete(NOTIFY_TABLE, id, callback -> {
                    if (callback.failed()) {
                        ValidationHelper.handleError(callback.cause(), asyncResultHandler);
                        return;
                    }
                    if (callback.result() == null) {
                        asyncResultHandler.handle(succeededFuture(GetPartyInfoByIdResponse.respond404WithTextPlain(id)));
                        return;
                    }

                    asyncResultHandler.handle(succeededFuture(DeletePartyInfoByIdResponse.respond204()));
                    //删掉延时队列的签到结束任务
                    //PartyAttendHandler.delJob(entity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                    TenantsTaskService.delJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyAttendHandler",entity);
                    //PartyEndHandler.delJob(entity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                    TenantsTaskService.delJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyEndHandler",entity);
                    CQLWrapper cqlWrapper = PartyUtil.CQLCreate("isDel = 0 and principalId = "+id+"*",-1,-1,NOTIFY_TABLE);
                    pg.delete(NOTIFY_TABLE,cqlWrapper,reply->{
                        PartyLogSave.saveLog("删除编号为【" + id + "】的活动", 4, null, okapiHeaders, asyncResultHandler, pg);
                    });
                });
            if (r.failed()) {
                logger.info(r.cause().getMessage());
            }
        });
    }


    @Override
    public void putPartyInfoById(String id, String lang, org.folio.rest.jaxrs.model.Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        String noteId = entity.getId();
        if (noteId != null && !noteId.equals(id)) {
            logger.error("Trying to change note Id from " + id + " to " + noteId);
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                    "Can not change the id");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
       // entity.setState(0);

        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
        pg.getById(NOTIFY_TABLE,entity.getId(),Party.class,reply->{
            if (reply.succeeded()){
                Party oldPartyDetail = reply.result();
                entity.setApproval(oldPartyDetail.getApproval());
                entity.setRemark(oldPartyDetail.getRemark());
                if (StrUtil.isBlankOrUndefined(oldPartyDetail.getFacId()) && !StrUtil.isNullOrUndefined(entity.getFacId())){
                new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(),entity.getFacName(),false,Integer.parseInt(entity.getFacCount()),replys-> {
                       if (replys.succeeded()){
                           updateVenueIdAndUpdateParty(id, entity, okapiHeaders, asyncResultHandler, pg, oldPartyDetail, replys,vertxContext);
                       }

                    });

                }else if(!StrUtil.isBlankOrUndefined(oldPartyDetail.getFacId()) && oldPartyDetail.getFacId().equals(entity.getFacId()) && !oldPartyDetail.getFacCount().equals(entity.getFacCount())){
                    Integer oldPartyDetailFacCount = Integer.parseInt(oldPartyDetail.getFacCount());
                    Integer entityFacCount = Integer.parseInt(entity.getFacCount());
                    if (oldPartyDetailFacCount > entityFacCount){
                        entityFacCount = oldPartyDetailFacCount - entityFacCount;
                        new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(), entity.getFacName(), true, entityFacCount, replys -> {
                            updateVenueIdAndUpdateParty(id, entity, okapiHeaders, asyncResultHandler, pg, oldPartyDetail, replys, vertxContext);
                        });
                    }else if(oldPartyDetailFacCount < entityFacCount){
                        entityFacCount=entityFacCount - oldPartyDetailFacCount;
                       new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(),entity.getFacName(),false,entityFacCount,replys-> {
                            updateVenueIdAndUpdateParty(id, entity, okapiHeaders, asyncResultHandler, pg, oldPartyDetail, replys,vertxContext);


                        });
                    }
                }else if (!StrUtil.isBlankOrUndefined(oldPartyDetail.getFacId()) && !oldPartyDetail.getFacId().equals(entity.getFacId())){
                   new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getFacId(),entity.getFacName(),false,Integer.parseInt(entity.getFacCount()),replys-> {

                        updateVenueIdAndUpdateParty(id, entity, okapiHeaders, asyncResultHandler, pg, oldPartyDetail, replys,vertxContext);

                    });
                   new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(oldPartyDetail.getFacId(),oldPartyDetail.getFacName(),true,Integer.parseInt(oldPartyDetail.getFacCount()),replys-> {

                        if (replys.failed()){
                            logger.info(replys.cause());
                            return;
                        }

                    });
                }else {
                    if(oldPartyDetail.getVenueId().equals(entity.getVenueId())){
                        updateParty(id, entity, okapiHeaders, asyncResultHandler, pg);
                    }else{
                        updateVenueIdAndParty(id, entity, okapiHeaders, asyncResultHandler, pg, oldPartyDetail, reply,vertxContext);
                    }

                }

            }else{
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }
        });


       //
    }

    private void updateVenueIdAndUpdateParty(String id, Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, PostgresClient pg, Party oldPartyDetail, AsyncResult<Auxiliary> replys, Context vertxContext) {
        if (replys.succeeded()) {
            if (!entity.getVenueId().equals(oldPartyDetail.getVenueId())) {
               new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getVenueId(), entity.getVenue(), false, Integer.parseInt(entity.getVenueCount()), r -> {
                    if (r.succeeded()) {
                        updateParty(id, entity, okapiHeaders, asyncResultHandler, pg);
                        //修改旧的
                        new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(oldPartyDetail.getVenueId(), oldPartyDetail.getVenue(), true, Integer.parseInt(oldPartyDetail.getVenueCount()), rs -> {

                            if (rs.failed()) {
                                logger.info(rs.cause());
                            }

                        });
                    } else {
                        ValidationHelper.handleError(replys.cause(), asyncResultHandler);
                    }

                });

            } else {
                updateParty(id, entity, okapiHeaders, asyncResultHandler, pg);
            }
        } else {
            ValidationHelper.handleError(replys.cause(), asyncResultHandler);
        }
    }
    private void updateVenueIdAndParty(String id, Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, PostgresClient pg, Party oldPartyDetail, AsyncResult<Party> replys, Context vertxContext) {
        if (replys.succeeded()) {
            if (!entity.getVenueId().equals(oldPartyDetail.getVenueId())) {
                new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(entity.getVenueId(), entity.getVenue(), false, Integer.parseInt(entity.getVenueCount()), r -> {
                    if (r.succeeded()) {
                        updateParty(id, entity, okapiHeaders, asyncResultHandler, pg);
                        //修改旧的
                        new AuxiliaryUpdateService(vertxContext, okapiHeaders).updateAuxiliary(oldPartyDetail.getVenueId(), oldPartyDetail.getVenue(), true, Integer.parseInt(oldPartyDetail.getVenueCount()), rs -> {

                            if (rs.failed()) {
                                logger.info(rs.cause());
                            }

                        });
                    } else {
                        ValidationHelper.handleError(replys.cause(), asyncResultHandler);
                    }

                });

            } else {
                updateParty(id, entity, okapiHeaders, asyncResultHandler, pg);
            }
        } else {
            ValidationHelper.handleError(replys.cause(), asyncResultHandler);
        }
    }
    private void updateParty(String id, Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, PostgresClient pg) {
        pg.update(NOTIFY_TABLE, entity, id,
                        reply -> {
                            if (reply.succeeded()) {
                                if (reply.result().getUpdated() == 0) {
                                    asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse
                                            .respond404WithTextPlain(id)));
                                } else { // all ok
                                    asyncResultHandler.handle(succeededFuture(
                                            PutPartyInfoByIdResponse.respond204()));
                                   // PartyAttendHandler.updatePartyAttendJob(entity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                                    TenantsTaskService.updatePartyAttendJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyAttendHandler",entity);
                                    TenantsTaskService.updateJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyEndHandler",entity);
                                    //PartyEndHandler.updateJob(entity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                                    PartyLogSave.saveLog("更新名称为【" + entity.getPartyName() + "】的活动", 3, entity.getMetadata(), entity.getOperator(), okapiHeaders, asyncResultHandler, pg);
                                }
                            } else {
                                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                            }
                        });
    }


    @Override
    public void putPartyInfoApproveById(String id, String lang, Party entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        String noteId = entity.getId();
        if (noteId != null && !noteId.equals(id)) {
            logger.error("Trying to change note Id from " + id + " to " + noteId);
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                    "Can not change the id");
            asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);

        pg.getById(NOTIFY_TABLE,entity.getId(),Party.class,reply->{
            if(reply.succeeded()){
                Party result = reply.result();

                if (result.getApproval() == 1){
                    Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                            "这个活动已经被审核通过，无需重复审核");
                    asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond404WithTextPlain(valErr)));
                    return;
                }
                String tmpStart = DateUtil.parse(result.getPartyStartDate()).toString("yyyy-MM-dd");
                String tmpEnd = DateUtil.parse(result.getPartyEndDate()).toString("yyyy-MM-dd");
                Boolean boo = false;
                if (entity.getApproval() ==1){

                    if (!tmpStart.equals(tmpEnd)){
                        boo = true;
                    }
                }
                entity.setState(0);
                entity.setPrincipalId(entity.getId());
                Boolean finalBoo = boo;
                Party reserveEntity = entity;
                pg.update(NOTIFY_TABLE, entity, id,
                        replyUpdate -> {
                            if (replyUpdate.succeeded()) {
                                if (replyUpdate.result().getUpdated() == 0) {
                                    asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse
                                            .respond404WithTextPlain(id)));
                                } else {

                                    //审核活动为 通过
                                    if (  reserveEntity.getApproval() ==1  ){
                                        //如果当天签到过期则会放在队列中,处理已报名读者的签到状态
                                       // PartyAttendHandler.setJob(reserveEntity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT), vertxContext.owner());
                                        TenantsTaskService.setJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyAttendHandler",reserveEntity );
                                        //如果活动当天到期,则释放活动过程中使用的资源
                                        TenantsTaskService.setJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyEndHandler",reserveEntity );
                                        //添加报名准备开始的活动
                                        TenantsTaskService.setJob(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"reserveStation",reserveEntity );
                                      //  PartyEndHandler.setJob(reserveEntity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT) );
                                        //添加报名准备开始的活动
                                       // ReserveStation.setJob(reserveEntity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT), vertxContext.owner());
                                        //复制活动
                                        if (finalBoo){
                                            List<String> dayList = LocalDateUtil.getDays(tmpStart, tmpEnd);
                                            String time = DateUtil.parse(result.getPartyStartDate()).toString("HH:mm:ss");
                                            result.setIsCalendar(1);
                                            result.setApproval(1);
                                            result.setPrincipalId(entity.getId());
                                            List<Party> calendarList = new ArrayList<>();
                                            //日期控制 生成跨日活动
                                            dayList.forEach(a->{
                                                Party temp = new Party();
                                                result.setPartyStartDate(a+" "+time);
                                                BeanUtil.copyProperties(result,temp);
                                                temp.setId(UUID.randomUUID().toString());
                                                calendarList.add(temp);
                                            });
                                            pg.saveBatch(NOTIFY_TABLE,calendarList,re->{
                                                asyncResultHandler.handle(succeededFuture(
                                                        PutPartyInfoByIdResponse.respond204()));
                                                PartyLogSave.saveLog("审核名称为【" + reserveEntity.getPartyName() + "】的活动", 3, reserveEntity.getMetadata(), reserveEntity.getOperator(), okapiHeaders, asyncResultHandler, pg);

                                            });
                                        }

                                    }else{
                                        //审核活动为不通过
                                        //检查是否在队列中,如果在则删除
                                        TenantsTaskService.removeAndFreed(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyEndHandler",reserveEntity);
                                        //PartyEndHandler.removeAndFreed(reserveEntity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                                        TenantsTaskService.removeAndFreed(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"partyAttendHandler",reserveEntity);
                                        TenantsTaskService.removeAndFreed(okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT),"reserveStation",reserveEntity);
                                        //PartyAttendHandler.removeAndFreed(reserveEntity, okapiHeaders.get(RestVerticle.OKAPI_HEADER_TENANT));
                                       // ReserveStation.removeAndFreed(reserveEntity.getId());
                                        asyncResultHandler.handle(succeededFuture(
                                                PutPartyInfoByIdResponse.respond204()));
                                        PartyLogSave.saveLog("审核名称为【" + reserveEntity.getPartyName() + "】的活动", 3, reserveEntity.getMetadata(), reserveEntity.getOperator(), okapiHeaders, asyncResultHandler, pg);

                                    }
                                    //通知 审核情况
                                    try {
                                        if ("1".equals(reserveEntity.getApproval().toString())){
                                            INotify.create(okapiHeaders,vertxContext,"2","").notifyCenter(reserveEntity,3);
                                        }
                                        if ("2".equals(reserveEntity.getApproval().toString())){
                                            INotify.create(okapiHeaders,vertxContext,"2","").notifyCenter(reserveEntity,4);
                                        }

                                    } catch (FieldException e) {
                                        e.printStackTrace();
                                    }
                                    asyncResultHandler.handle(succeededFuture(PutPartyInfoByIdResponse.respond204()));
                                }
                            } else {
                                ValidationHelper.handleError(replyUpdate.cause(), asyncResultHandler);
                            }
                        });
            }else{

            }
        });
   }

    
}
